import store from '@/store'

/**
 * @param {Array} value
 * @returns {Boolean}
 * @example see @/views/permission/directive.vue
 */
export default function checkPermission(value) {
  if (value && typeof value === 'string' && value.length > 0) {
    const permission = store.state.permission.directives // 服务器传回的指令权限列表(url + role)
    const directive = value // 校验的内容，v-permission 传入的内容（v-permission="'/user/user/update'"）
    const roles = store.getters && store.getters.roles // 用户具有的角色

    let hasPermission = true
    permission.forEach(onePermission => {
      if (onePermission.url === directive) {
        hasPermission = false
        roles.forEach(userRole => {
          // 如果用户具有角色，就有权限
          if (onePermission.role.includes('|' + userRole + '|')) {
            hasPermission = true
            return
          }
        })
        return
      }
    })

    return hasPermission
  } else {
    return true
  }
}
